<template>
    <div class="addHouse">
        <div class="top">
            <!--下拉切换-->
            <div class="main" style="justify-content: space-between;flex-direction: inherit;">
                <div>{{ isEdit ? $t("text.House.l294") : $t("text.router.l24") }}</div>
                <el-button type="primary" @click="handleClick" style="width: 85px;height: 30px;" :loading="loading">{{
                    $t("text.House.l144") }}</el-button>
            </div>
        </div>
        <div class="main">
            <!--表单结构渲染-->
            <div v-if="isload">
                <div style="width: 100%;">
                    <div class="headTitle">{{ $t("text.PageData.l187") }}</div>
                    <div class="df">
                        <div style="padding-right: 15px;">
                            <div class="title"><span class="must">※</span>{{ $t("text.PageData.l188") }}</div>
                            <CommonSelectKey :dataList="areaIds1" @returnData="setData2"
                                :default="isEdit ? getAreaName(1, insertData.areaIds) : $t('text.PageData.l189')" isMust
                                :mustHit="$t('text.PageData.l189')" insertKey="areaIds" ref="child1"
                                :isSelect="insertData.areaIds == null ? false : isEdit">
                            </CommonSelectKey>
                        </div>

                        <div style="padding-right: 15px;">
                            <div class="title"><span class="must">※</span>{{ $t("text.PageData.l190") }}</div>
                            <CommonSelectKey :dataList="areaIds2" @returnData="setData3"
                                :default="isEdit ? getAreaName(2, insertData.areaIds) : $t('text.PageData.l191')" isMust
                                :mustHit="$t('text.PageData.l191')" insertKey="areaIds" ref="child2" :clear="clear1"
                                :isSelect="insertData.areaIds == null ? false : isEdit">
                            </CommonSelectKey>
                        </div>

                        <div style="padding-right: 15px;">
                            <div class="title"><span class="must">※</span>{{ $t("text.PageData.l192") }}</div>
                            <CommonSelectKey :dataList="areaIds3" @returnData="setData4"
                                :default="isEdit ? getAreaName(3, insertData.areaIds) : $t('text.PageData.l193')" isMust
                                :mustHit="$t('text.PageData.l193')" insertKey="areaIds" ref="child3" :clear="clear2"
                                :isSelect="insertData.areaIds == null ? false : isEdit">
                            </CommonSelectKey>
                        </div>

                        <div style="width: 100%;"></div>

                        <div style="padding-right: 15px;">
                            <div class="title"><span class="must">※</span>{{ $t('text.PageData.l200') }}</div>
                            <CommonInputKey isMust :mustHit="$t('text.PageData.l201')" insertKey="name" ref="child5"
                                @returnData="setData" :isNumber="0" :default="insertData.name">
                            </CommonInputKey>
                        </div>


                        <div style="padding-right: 15px;">
                            <div class="title">{{ $t('text.PageData.l202') }}</div>
                            <CommonInputKey insertKey="address" @returnData="setData" :isNumber="0"
                                :default="insertData.address">
                            </CommonInputKey>
                        </div>
                        <div style="padding-right: 106px;">
                            <DialogLayout46 @returnData="setMapAddress" :mapCoordinates="mapCoordinates" v-if="mapType">
                            </DialogLayout46>
                            <DialogLayout36 @returnData="setMapAddress" :mapCoordinates="mapCoordinates" v-else>
                            </DialogLayout36>
                        </div>

                        <div style="width: 100%;"></div>

                        <div style="padding-right: 15px;">
                            <div class="title"><span class="must">※</span>{{ $t('text.PageData.l197') }}</div>
                            <CommonSelectKey :dataList="dictionaryTree.saleStatusNews" @returnData="setData" isMust
                                :mustHit="$t('text.PageData.l198')" ref="child4"
                                :default="isEdit ? insertData.saleStatus == null || insertData.saleStatus == '' ? $t('text.PageData.l199') : insertData.saleStatus : $t('text.PageData.l199')"
                                :isSelect="insertData.saleStatus == null ? false : isEdit" insertKey="saleStatus">
                            </CommonSelectKey>
                        </div>

                        <div style="padding-right: 15px;">
                            <div class="title">{{ $t('text.PageData.l203') }}</div>
                            <CommonInputTime insertKey="openTime" @returnData="setData"
                                :default="isEdit ? insertData.openTime == null || insertData.openTime == '' ? $t('text.PageData.l34') : insertData.openTime : $t('text.PageData.l34')">
                            </CommonInputTime>
                        </div>


                        <div style="padding-right: 15px;">
                            <div class="title">{{ $t('text.PageData.l204') }}</div>
                            <CommonInputTime :leftText="$t('text.PageData.l34')" insertKey="deliverTime"
                                @returnData="setData"
                                :default="isEdit ? insertData.deliverTime == null || insertData.deliverTime == '' ? $t('text.PageData.l34') : insertData.deliverTime : $t('text.PageData.l34')">
                            </CommonInputTime>
                        </div>

                    </div>
                </div>


                <div v-for="(s, index1) in addHousePage" v-bind:key="s.headTitle" style="width: 100%;">
                    <div class="headTitle">{{ s.headTitle }}</div>
                    <div class="df">
                        <div v-for="(item, index2) in s.data" v-bind:key="item.title"
                            :style="item.type == 'radio'||item.type=='br' ? { paddingRight: '15px', width: '100%' } : { paddingRight: '15px' }">

                            <div class="title" v-if="item.type!='br'"><span class="must" v-if="item.isMust">※</span>{{ item.title }}</div>
                            <CommonInputKey v-if="item.type == 'input'" :leftText="item.defaultUnit" :isMust="item.isMust"
                                :mustHit="item.mustHit" :insertKey="item.insertKey" @returnData="setData"
                                :isNumber="item.isNumber" :ref="'childs' + index1 + index2" :min="item.min"
                                :default="insertData[item.insertKey]">
                            </CommonInputKey>

                            <CommonSelectKey v-if="item.type == 'select'" :dataList="dictionaryTree[item.dictionaryKey]"
                                :isMust="item.isMust" :mustHit="item.mustHit" :ref="'childs' + index1 + index2"
                                :default="isEdit ? insertData[item.insertKey] == null || insertData[item.insertKey] == '' ? item.default : insertData[item.insertKey] : item.default"
                                :isSelect="insertData[item.insertKey] == null ? false : isEdit" :insertKey="item.insertKey"
                                @returnData="setData">
                            </CommonSelectKey>

                            <CommonRangeInput v-if="item.type == 'rangeInput'"
                                :dataList="dictionaryTree[item.dictionaryKey]" :isMust="item.isMust" :mustHit="item.mustHit"
                                :insertKey="item.insertKey" @returnData="setData" @clearData="clearData"
                                :leftText="item.defaultUnit" :ref="'childs' + index1 + index2"
                                :default1="insertData[item.insertKey.split(',')[0]]" :max="item.max"
                                :default2="insertData[item.insertKey.split(',')[1]]">
                            </CommonRangeInput>

                            <CommonRadioKey v-if="item.type == 'radio'" :dataList="dictionaryTree[item.dictionaryKey]"
                                :isMust="item.isMust" :mustHit="item.mustHit" :insertKey="item.insertKey"
                                @returnData="setData" :ref="'childs' + index1 + index2"
                                :isValue="item.dictionaryKey == 'roomType'||item.dictionaryKey=='houseType' ? true : false"
                                :default="insertData[item.insertKey] == null ? [] : item.dictionaryKey == 'roomType'||item.dictionaryKey=='houseType' ? getRadioDict(insertData[item.insertKey].split(','), item.dictionaryKey) : insertData[item.insertKey].split(',')">
                            </CommonRadioKey>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
    

<script>
import { ElMessage } from 'element-plus'
import { addNewHousePage } from '../../itemList';
import { newsGetInsertDropdownData, newsInsert, trendsUpdate, areaFindTreeAll } from '../../http/api'
import CommonInputKey from '../../components/input/CommonInputKey.vue';
import CommonSelectKey from '../../components/input/CommonSelectKey.vue';
import CommonRadioKey from '../../components/input/CommonRadioKey.vue';
import CommonInputTime from '../../components/input/CommonInputTime.vue';
import CommonRangeInput from '../../components/input/CommonRangeInput.vue';
import DialogLayout36 from '../../components/dialogLayout/DialogLayout36.vue'
import DialogLayout46 from '@/components/dialogLayout/DialogLayout46.vue';
export default {
    name: 'AddNeighbourhoods',
    components: {
        CommonRadioKey: CommonRadioKey,
        CommonInputKey: CommonInputKey,
        CommonSelectKey: CommonSelectKey,
        DialogLayout36: DialogLayout36,
        CommonInputTime: CommonInputTime,
        CommonRangeInput: CommonRangeInput,
        DialogLayout46
    },
    data() {
        return {
            addHousePage: addNewHousePage,
            dictionaryTree: {},
            isload: false,
            insertData: {},
            areaIds1: [],
            areaIds2: [],
            areaIds3: [],
            areaIdsValue1: '',
            areaIdsValue2: '',
            areaIdsValue3: '',
            clear1: false,
            clear2: false,
            isEdit: false,
            mapCoordinates: [],
            mapType: localStorage.getItem('mapType') == 'mapkit' ? true : false,
            loading: false
        }
    },
    mounted() {

        if (this.$route.query.edit == 'true' && localStorage.getItem("addNewHouse") != null) {
            this.isEdit = true
            this.insertData = JSON.parse(localStorage.getItem("addNewHouse"))
            if (this.insertData.mapCoordinates && this.insertData.mapCoordinates != "") {
                this.mapCoordinates = this.insertData.mapCoordinates.split(",")
            }
            console.log(JSON.parse(localStorage.getItem("addNewHouse")))
        }

        newsGetInsertDropdownData().then(res => {
            if (res !== undefined) {
                this.dictionaryTree = res
                console.log(res)
                areaFindTreeAll().then(res => {
                    if (res !== undefined) {
                        this.areaIds1 = res
                        this.isload = true
                    }
                }).catch()
            }
        }).catch()
    },
    methods: {
        handleClick() {
            let flag = true
            for (let index = 1; index <= 5; index++) {
                const childRef = this.$refs['child' + index]
                if (childRef && !childRef.inputReturn()) {
                    flag = flag && false
                }
            }
            this.addHousePage.forEach((element, index1) => {
                element.data.forEach((item, index2) => {
                    const childRef = this.$refs['childs' + index1 + index2]
                    if (childRef && childRef.length > 0 && !childRef[0].inputReturn()) {
                        flag = flag && false
                    }
                });
            });
            if (flag) {
                this.insert()
            } else {
                ElMessage.error({
                    showClose: true,
                    message: this.$t('text.Common.l999'),
                    type: 'error',
                })
            }
        },

        //多选框值转换
        getRadioDict(list, key) {
            let dict = []
            let data
            list.forEach(element => {
                data = this.dictionaryTree[key].filter(v => v.dictValue === element)
                if (data.length > 0) {
                    dict = [...dict, this.dictionaryTree[key].filter(v => v.dictValue === element)[0].dictName]
                }
            });
            return dict
        },
        //获取名称
        getAreaName(level, ids) {
            let temp = ids.split(",")
            if (temp.length >= 1 && level == 1)
                return this.findNodeByLevel(this.areaIds1, 1, temp[0])
            if (temp.length >= 2 && level == 2)
                return this.findNodeByLevel(this.areaIds1, 2, temp[1])
            if (temp.length >= 3 && level == 3)
                return this.findNodeByLevel(this.areaIds1, 3, temp[2])
        },

        //通过区域id反向查找名称进行回显
        findNodeByLevel(data, level, id) {
            if (level === 1) {
                return data.find(item => item.id === id)?.areaName;
            }
            for (let item of data) {
                if (item.children) {
                    const result = this.findNodeByLevel(item.children, level - 1, id);
                    if (result) {
                        return result;
                    }
                }
            }
            return '';
        },
        //提交上传
        insert() {
            let temp = []
            if (this.areaIdsValue1 != '') {
                temp.push(this.areaIdsValue1)
            }
            if (this.areaIdsValue2 != '') {
                temp.push(this.areaIdsValue2)
            }
            if (this.areaIdsValue3 != '') {
                temp.push(this.areaIdsValue3)
            }
            if (!this.isEdit) {
                if (temp.length == 3) {
                    this.loading = true
                    this.insertData = { ...this.insertData, ...{ areaIds: temp.join(",") } }
                    newsInsert(this.insertData).then(res => {
                        this.loading = false
                        if (res !== undefined) {
                            ElMessage.success({
                                showClose: true,
                                message: this.$t("text.Customer.l1"),
                                type: 'success',
                            })
                            this.$router.back()
                        }
                    }).catch()
                } else {
                    ElMessage.error({
                        showClose: true,
                        message: this.$t('text.PageData.l191'),
                        type: 'error',
                    })
                }
            }

            if (this.isEdit) {
                if (temp.length == 3) {
                    this.loading = true
                    this.insertData = { ...this.insertData, ...{ areaIds: temp.join(",") } }
                    trendsUpdate(this.insertData).then(res => {
                        this.loading = false
                        if (res !== undefined) {
                            ElMessage.success({
                                showClose: true,
                                message: this.$t('text.Common.l3'),
                                type: 'success',
                            })
                            this.$router.back()
                        }
                    }).catch()
                } else if (temp.length == 0) {
                    this.loading = true
                    trendsUpdate(this.insertData).then(res => {
                        this.loading = false
                        if (res !== undefined) {
                            ElMessage.success({
                                showClose: true,
                                message: this.$t('text.Common.l3'),
                                type: 'success',
                            })
                            this.$router.back()
                        }
                    }).catch()
                } else {
                    ElMessage.error({
                        showClose: true,
                        message: this.$t('text.PageData.l191'),
                        type: 'error',
                    })
                }
            }
        },
        //接收返回值
        setData(obj) {
            this.insertData = { ...this.insertData, ...obj }
            console.log(this.insertData)
        },
        setData2(obj) {
            this.areaIdsValue1 = obj.areaIds
        },
        setData3(obj) {
            this.areaIdsValue2 = obj.areaIds
        },
        setData4(obj) {
            this.areaIdsValue3 = obj.areaIds
        },
        setMapAddress(form) {
            let obj = {
                address: form.address,
                mapCoordinates: form.lng + "," + form.lat,
            }
            this.insertData = { ...this.insertData, ...obj }
        },

        clearData(obj) {
            const objKeys = Object.keys(obj)
            this.insertData = Object.keys(this.insertData).reduce((acc, key) => {
                if (!objKeys.includes(key)) {
                    acc[key] = this.insertData[key]
                }
                return acc
            }, {})
            console.log(this.insertData)
        },

    },
    watch: {
        areaIdsValue1: {
            handler() {
                let temp = this.areaIds1.filter(v => v.dictValue === this.areaIdsValue1)
                if (temp.length > 0) {
                    this.areaIds2 = []
                    this.areaIds3 = []
                    this.areaIds2 = temp[0].children
                }
                this.clear1 = !this.clear1
                this.clear2 = !this.clear2
            }
        },
        areaIdsValue2: {
            handler() {
                let temp = this.areaIds2.filter(v => v.dictValue === this.areaIdsValue2)
                if (temp.length > 0) {
                    this.areaIds3 = []
                    this.areaIds3 = temp[0].children
                }
                this.clear2 = !this.clear2
            }
        }
    },
    computed: {

    }

}
</script>
    
<style scoped>
.addHouse {
    width: 100%;
}

.main {
    /* width: 100%; */
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 700px;
    margin: 0 auto;
}

.w {
    width: 100%;
}

.df {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    border-bottom: 1px solid rgb(220, 223, 230);
    padding-bottom: 25px;
}

.title {
    font-size: 12px;
    color: black;
    text-align: left;
    display: flex;
    align-items: center;
    padding-top: 15px;
    padding-bottom: 5px;
    font-weight: 600;
}

.top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    border-bottom: 1px solid rgb(220, 223, 230);
    padding-top: 7px;
    padding-bottom: 7px;
    position: sticky;
    top: 29px;
    background: white;
    z-index: 53;
    box-shadow: 1px 1px 10px 5px #f8f8f8
}

.headTitle {
    font-size: 14px;
    color: #aaa;
    text-align: left;
    padding-top: 20px
}

.must {
    font-size: 12px;
    color: red;
    padding-right: 5px;
}

.mapImg {
    height: 17px;
    width: 17px;
    padding-right: 3px;
}
</style>